// utils.js

// 引入 CryptoJS 库
import CryptoJS from 'crypto-js';


export function generateToken(params, key) {
    const { et, method, res, version } = params;

    // 1. 准备用于签名的字符串
    const stringForSignature = `${et}\n${method}\n${res}\n${version}`;

    // 2. 对 key 进行 Base64 解码
    const decodedKey = CryptoJS.enc.Base64.parse(key);

    // 3. 计算签名
    let hash;
    if (method === 'md5') {
        hash = CryptoJS.HmacMD5(stringForSignature, decodedKey);
    } else if (method === 'sha1') {
        hash = CryptoJS.HmacSHA1(stringForSignature, decodedKey);
    } else if (method === 'sha256') {
        hash = CryptoJS.HmacSHA256(stringForSignature, decodedKey);
    } else {
        throw new Error(`Unsupported method: ${method}`);
    }
    const sign = CryptoJS.enc.Base64.stringify(hash);

    // 4. 构建最终的 Token 并进行 URL 编码
    const tokenParams = {
        version,
        res,
        et,
        method,
        sign
    };

    const queryString = Object.keys(tokenParams)
        .map(key => `${key}=${encodeURIComponent(tokenParams[key])}`)
        .join('&');

    return queryString;
}




export function greet(name) {
  return `Hello, ${name}!`;
}